﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.LightSwitch.Details.Client;
using Microsoft.LightSwitch;

using ExtensionsMadeEasy.Utilities.Extensions;
using System.ComponentModel;
using System.Collections.Generic;

namespace ExtensionsMadeEasy.Presentation.Screens
{
    public static class ScreenCollectionFuzzySearch
    {
        public static void MakeFuzzy(this IScreenCollectionProperty t)
        {
            //Use the main dispatcher (who owns the CollectionLoader) to listen for changes
            Microsoft.LightSwitch.Threading.Dispatchers.Main.BeginInvoke(
                () =>
                {
                    (t.Loader as INotifyPropertyChanged)
                        .PropertyChanged += (new FuzzyMakerListener()).loader_PropertyChanged;
                }
            );
        }
        internal sealed class FuzzyMakerListener
        {
            private bool ignoreNextSearchTermsChangedEvent = false;
            public void loader_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
            {
                if (e.PropertyName == "SearchTerms")
                {
                    //Upon change, we replace the SearchTerms. This in turn, fires the PropertyChanged event again.
                    //To avoid endless loops: behold the ignoreNextSearchTermChangedEvent boolean!
                    if (ignoreNextSearchTermsChangedEvent)
                    {
                        ignoreNextSearchTermsChangedEvent = false;
                    }
                    else
                    {

                        IScreenCollectionPropertyLoader loader = sender as IScreenCollectionPropertyLoader;
                        List<SearchTerm> fuzzyTerms = new List<SearchTerm>();
                        foreach (var searchTerm in loader.SearchTerms)
                        {
                            fuzzyTerms.Add(
                                new SearchTerm(searchTerm.Value.MakeFuzzy())
                                );
                        }
                        loader.SetSearchTerms(fuzzyTerms);
                        ignoreNextSearchTermsChangedEvent = true;
                    }
                }
            }
        }
    }
}
